<template>
  <view class="pay-wrap u-skeleton" :data-theme="globPrimary">
    <u-navbar title="确认订单" :custom-back="onBack"></u-navbar>
    <block v-if="productInfo.product.fictitious == 0">
      <!-- 无地址 -->
      <view
        v-if="$u.test.empty(productAddress)"
        class="pay-address u-flex u-skeleton-rect"
        @click="onAddress"
      >
        <view class="address-left">
          <u-icon custom-prefix="edu-icon" name="daohangdizhi" color="#ffffff"></u-icon>
        </view>
        <view class="address-body">
          <view class="name">添加收货地址</view>
        </view>
        <view class="address-right">
          <u-icon name="arrow-right" color="#B7BAC1" size="28"></u-icon>
        </view>
      </view>
      <!-- 已有地址 -->
      <view v-else class="pay-address u-flex" @click="onAddress">
        <view class="address-left">
          <u-icon custom-prefix="edu-icon" name="daohangdizhi" color="#ffffff"></u-icon>
        </view>
        <view class="address-body">
          <view class="u-flex">
            <view class="name">{{ productAddress.consignee }}</view>
            <view class="phone">{{ productAddress.phone | formatMask }}</view>
          </view>
          <view class="address"
            >{{ productAddress.areatext }}
            {{ productAddress.address }}
          </view>
        </view>
        <view class="address-right">
          <u-icon name="arrow-right" color="#B7BAC1" size="28"></u-icon>
        </view>
      </view>
    </block>

    <view class="pay-product u-skeleton-rect">
      <view class="picture">
        <edu-image :width="132" :height="132" :src="productInfo.product.cover_url"></edu-image>
      </view>
      <view class="desc">
        <view class="title u-line-2">{{ productInfo.product.title }}</view>
        <view class="u-flex">
          <block v-if="productInfo.product.credit_price > 0 && productInfo.product.cash_price > 0">
            <view class="price">{{ productInfo.product.credit_price }}</view>
            <view class="unit">积分+{{ projectSetting.appMoneySymbol }}</view>
            <view class="price">{{ productInfo.product.cash_price }}</view>
          </block>
          <block v-else-if="productInfo.product.credit_price > 0">
            <view class="price">{{ productInfo.product.credit_price }}</view>
            <view class="unit">积分</view>
          </block>
          <block v-else-if="productInfo.product.cash_price > 0">
            <view class="unit">{{ projectSetting.appMoneySymbol }}</view>
            <view class="price">{{ productInfo.product.cash_price }}</view>
          </block>
          <view class="free" v-else>免费</view>
          <!-- <view class="time">永久有效</view> -->
        </view>
      </view>
    </view>

    <view class="pay-number u-skeleton-rect">
      <view class="number-wrap u-flex u-row-between u-border-bottom">
        <view class="txt">数量</view>
        <u-number-box
          v-model="productNumber"
          :min="1"
          :max="99"
          bg-color="#ffffff"
          @change="handleNumberChange"
        ></u-number-box>
      </view>
    </view>

    <view class="pay-money u-flex u-row-between u-skeleton-rect">
      <view class="txt">运费</view>
      <view class="price">{{ productInfo.product.carriage | formatCurrency }}</view>
    </view>

    <view class="pay-integral u-flex u-row-between u-skeleton-rect">
      <view class="u-flex" @click="openIntegralModal">
        <view class="txt">积分</view>
        <u-icon name="info-circle" color="#909399" size="28"></u-icon>
      </view>
      <view class="u-flex">
        <view class="num"
          >共{{ productInfo.credit.user_credit || 0 }}，本次可用{{ payCredit }}</view
        >
        <u-checkbox
          v-model="productCredit"
          :active-color="globPrimaryColor"
          shape="circle"
          size="40"
          @change="handleCheckboxChange"
        ></u-checkbox>
      </view>
    </view>

    <view class="pay-footer u-flex" v-if="!loading">
      <view class="txt">实付金额：</view>
      <view class="price">{{ payPrice | formatCurrency }}</view>
      <view class="btn">
        <edu-button type="primary" shape="circle" @click="submitOrder" :disabled="disabled"
          >提交订单</edu-button
        >
      </view>
    </view>

    <!-- 积分使用规则 -->
    <u-modal
      v-model="integralVisible"
      title="积分使用规则"
      confirm-text="我知道了"
      :confirm-style="integralConfirmStyle"
    >
      <view class="integral-rule-content">
        <view>1，订单可使用积分+现金支付； </view>
        <view>2，订单抵扣积分不能超过商品最高积分抵扣数量； </view>
        <view>3，{{ productInfo.credit.ratio }}积分抵扣1元。</view>
      </view>
    </u-modal>

    <u-skeleton :loading="loading" el-color="#f7f7f7" bg-color="transparent"></u-skeleton>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
import projectSetting from '@/settings/projectSetting.js'
export default {
  data() {
    return {
      projectSetting,
      loading: true,
      integralVisible: false, // 积分规则提示可见性
      productNumber: 1, // 商品选择的数量
      productCredit: true, // 商品是否使用积分
      productId: 0, // 商品id
      productInfo: {
        address: {},
        credit: {
          user_credit: 0,
          max_credit: 0,
          arr: [],
        },
        product: {
          carriage: 0,
          cash_price: 0,
          cover_url: '',
          credit_price: 0,
          fictitious: 0,
          title: '',
        },
      }, // 商品订单数据
      payCredit: 0, // 支付可用积分
      payPrice: 0, // 支付价格
      disabled: false,
      productAddress: {},
    }
  },
  computed: {
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
    }),
    integralConfirmStyle() {
      let style = {
        width: '260rpx',
        height: '64rpx',
        background: this.globPrimaryColor,
        borderRadius: '36px',
        fontSize: '28rpx',
        color: '#FFFFFF',
        lineHeight: '64rpx',
        margin: '24rpx auto 32rpx',
        flex: 'inherit',
      }
      return style
    },
  },
  // 监听页面返回
  onBackPress(options) {
    if (options.from === 'navigateBack') {
      return false
    }
    this.onBack()
    return true
  },
  onLoad(options) {
    this.productId = options.id
    this.getOrderInfo()
  },
  mounted() {
    // 切换地址
    uni.$on('chooseAddress', (address) => {
      this.productAddress = JSON.parse(address)
    })
  },
  onUnload() {
    // 移除监听事件
    uni.$off('chooseAddress')
  },
  methods: {
    getOrderInfo() {
      this.$edu.api
        .getMallOrderFetch({
          product: this.productId,
        })
        .then((res) => {
          const { data } = res
          this.productInfo = data
          if (this.$u.test.empty(this.productAddress)) {
            this.productAddress = data.address
          }
          setTimeout(() => {
            this.loading = false
            this.handleCredit()
          }, 50)
        })
        .catch((err) => {
          this.$u.toast(err.msg)
        })
    },
    // 提交订单
    submitOrder() {
      let addr_id = 0
      if (this.productInfo.product.fictitious == 0) {
        if (this.$u.test.empty(this.productAddress)) {
          this.$u.toast('请添加收货地址')
          return
        } else {
          addr_id = this.productAddress.id
        }
      }
      this.disabled = true
      this.$edu.api
        .postMallOrderSubmit({
          id: this.productId,
          num: this.productNumber,
          credit: this.payCredit,
          addr_id: addr_id,
        })
        .then((res) => {
          const { data } = res
          // 是否需要支付
          if (data.need_pay == 1) {
            let params = {
              id: this.productId,
              no: data.order_no,
              payment: data.payment,
              redirect_type: 'mall',
            }
            this.$u.route({
              type: 'redirectTo',
              url: 'pages/pay',
              params: params,
            })
          } else {
            this.onBack()
          }
          setTimeout(() => {
            this.disabled = false
          }, 50)
        })
        .catch((err) => {
          this.$u.toast(err.msg)
          setTimeout(() => {
            this.disabled = false
          }, 50)
        })
    },
    // 商品数量发生变化时
    handleNumberChange() {
      this.handleCredit()
    },
    // 是否使用积分变化时
    handleCheckboxChange(e) {
      this.productCredit = e.value
      this.handleCredit()
    },
    // 计算可用积分和商品支付价格
    handleCredit() {
      let productCredit = Number(this.productInfo.product.credit_price) // 单个商品的积分
      let productPrice = Number(this.productInfo.product.cash_price) // 单个商品的价格
      let userCredit = Number(this.productInfo.credit.user_credit) || 0 // 用户的可使用的积分
      let productCreditRatio = Number(this.productInfo.credit.ratio) // 商品的积分比例
      let productCarriage = Number(this.productInfo.product.carriage) // 商品运费
      let currentCredit = productCredit * this.productNumber // 总积分
      let currentPrice = productPrice * this.productNumber // 总价
      let credit = 0 // 支付的积分
      let price = 0 // 支付的价格
      // 是否使用积分
      if (this.productCredit) {
        // 如果用户的积分大于等于选择的总积分
        if (userCredit >= currentCredit) {
          price = currentPrice + productCarriage
          credit = currentCredit
        } else {
          // 积分不够时，计算积分的差价加上商品的价格就是支付价格，然后加上运费
          price = (currentCredit - userCredit) / productCreditRatio + currentPrice + productCarriage
          credit = userCredit
        }
      } else {
        price = currentCredit / productCreditRatio + currentPrice + productCarriage
        credit = 0
      }
      this.payCredit = credit
      this.payPrice = Math.floor(price * 100) / 100 // 不四舍五入保留两位小数
    },
    // 打开积分规则弹框
    openIntegralModal() {
      this.integralVisible = true
    },
    // 地址
    onAddress() {
      let query = {
        id: this.productId,
      }
      if (!this.$u.test.empty(this.productAddress)) {
        query.address = this.productAddress.id
      }
      this.$u.route('pageUser/address/index', query)
    },
    // 返回上一页
    onBack() {
      let pages = getCurrentPages()
      let page = pages[pages.length - 2]
      if (this.$u.test.empty(page)) {
        this.$u.route({
          type: 'reLaunch',
          url: 'pageFound/mall/details',
          params: {
            id: this.productId,
          },
        })
      } else {
        this.$u.route({ type: 'back' })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.pay-address {
  margin-bottom: 20rpx;
  padding: 24rpx 30rpx;
  background: #ffffff;
  .address-left {
    width: 56rpx;
    height: 56rpx;
    border-radius: 100%;
    @include bg-color();
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .address-body {
    flex: 1;
    margin: 0 32rpx;
    .name {
      font-size: 30rpx;
      font-weight: 500;
      color: $edu-main-color;
    }
    .phone {
      margin-left: 24rpx;
      font-size: 26rpx;
      font-weight: 400;
      color: $edu-main-color;
    }
    .address {
      margin-top: 12rpx;
      font-size: 26rpx;
      font-weight: 400;
      color: $edu-tips-color;
      line-height: 37rpx;
    }
  }
}

.pay-product {
  padding: 32rpx 30rpx 17rpx;
  display: flex;
  background: #ffffff;
  .picture {
    border-radius: 6rpx;
    overflow: hidden;
  }
  .desc {
    padding: 6rpx 0;
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-left: 24rpx;
  }
  .title {
    font-size: 28rpx;
    font-weight: 400;
    color: $edu-main-color;
  }
  .price {
    font-size: 26rpx;
    font-weight: 500;
    color: $edu-price-color;
  }
  .unit {
    font-size: 22rpx;
    font-weight: 500;
    color: $edu-price-color;
  }
  .time {
    margin-left: auto;
    font-size: 22rpx;
    font-weight: 400;
    color: $edu-tips-color;
  }
  .free {
    font-size: 26rpx;
    font-weight: 500;
    color: $edu-free-color;
  }
}

.pay-number {
  padding-left: 30rpx;
  background: #ffffff;
  .number-wrap {
    padding: 27rpx 30rpx 27rpx 0;
  }
  .txt {
    font-size: 28rpx;
    font-weight: 400;
    color: $edu-main-color;
  }
  ::v-deep .u-numberbox {
    .u-icon-minus,
    .u-icon-plus {
      border: 1px solid #dcdfe6;
    }
    .u-number-input {
      border-style: solid;
      border-color: #dcdfe6;
      border-width: 1px 0;
      margin: 0;
      box-sizing: border-box;
    }
  }
}

.pay-money {
  padding: 30rpx;
  background: #ffffff;
  .txt {
    font-size: 28rpx;
    font-weight: 400;
    color: $edu-main-color;
  }
  .price {
    font-size: 26rpx;
    font-weight: 400;
    color: $edu-main-color;
  }
}

.pay-integral {
  margin-top: 22rpx;
  padding: 30rpx;
  background: #ffffff;
  .txt {
    margin-right: 8rpx;
    font-size: 28rpx;
    font-weight: 400;
    color: $edu-main-color;
  }
  .num {
    margin-right: 24rpx;
    font-size: 28rpx;
    font-weight: 400;
    color: $edu-main-color;
  }
  ::v-deep .u-checkbox__label {
    margin-right: 0;
    margin-left: 0;
  }
}

.pay-footer {
  padding: 13rpx 30rpx 13rpx 30rpx;
  padding-bottom: 13rpx;
  padding-bottom: calc(constant(safe-area-inset-bottom) + 13rpx);
  padding-bottom: calc(env(safe-area-inset-bottom) + 13rpx);
  background: #ffffff;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  .txt {
    font-size: 26rpx;
    font-weight: 400;
    color: $edu-main-color;
  }
  .price {
    font-size: 30rpx;
    font-weight: 500;
    color: $edu-price-color;
  }
  .btn {
    width: 220rpx;
    margin-left: auto;
  }
}

.integral-rule-content {
  padding: 24rpx 40rpx;
  font-size: 24rpx;
  font-weight: 400;
  color: $edu-main-color;
  line-height: 40rpx;
}
</style>
